﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core.Security;
using Medianamik.Globalization;
using Medianamik.Core.Sugar;
using Medianamik.UI.Controls;
using Medianamik.Core;
using System.Text;

namespace Medianamik.UI.UserControls
{
    public partial class PermissionSelector : System.Web.UI.UserControl
    {

        #region Fields

        List<Permission> _permissions;

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                _permissions = CompilePermissions();
            }
            else
            {
                List<GroupNode> groups = SecurityManager.GetAllGroups().ToList();
                groups.RemoveAll(g => g.ID.Equals(MedianamikGroups.SuperAdmins));
                BuildControl(groups);
            }
        }

        protected void applyToChildrenButton_ItemCommand(object source, CommandEventArgs e)
        {
            if (e.CommandName.Equals("ApplyToChildren"))
            {
                StringBuilder groupBuilder = new StringBuilder();

                foreach (RepeaterItem item in groupRepeater.Items)
                {
                    Guid key;

                    if ((item.ItemType == ListItemType.Item ||
                        item.ItemType == ListItemType.AlternatingItem) &&
                        StringHelper.IsGuid(((HiddenField)item.FindControl("dataFieldId")).Value, out key))
                    {
                        System.Web.UI.WebControls.CheckBox checkBox = ((System.Web.UI.WebControls.CheckBox)item.FindControl("groupCheckBox"));
                        if(checkBox.Checked)
                            groupBuilder.AppendFormat("{0},", key.ToString());
                        checkBox.Checked = false;
                    }
                }

                string groups = groupBuilder.ToString();

                if (groups.Length > 0)
                {
                    SecurityManager.ApplyTypePermissionsToChildren(ObjectId, groups.Substring(0, groups.Length - 1));
                }
            }
        }

        protected void groupRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item
                || e.Item.ItemType == ListItemType.AlternatingItem)
                && e.Item.DataItem != null)
            {

                GroupNode group = (GroupNode)e.Item.DataItem;

                InheritedPermission inheritedPermission = group.InheritedPermissions.
                    SingleOrDefault(p => p.ID.Equals(ObjectId));

                Permission permission = group.Permissions.
                    SingleOrDefault(p => p.ID.Equals(ObjectId));

                if (permission == null)
                {
                    ((GroupRadioButton)e.Item.FindControl("inheritedOption")).Checked = true;
                }
                else
                {
                    switch (permission.SecurityLevel)
                    {
                        case SecurityLevel.Read:
                            ((GroupRadioButton)e.Item.FindControl("readOption")).Checked = true;
                            break;
                        case SecurityLevel.Update:
                            ((GroupRadioButton)e.Item.FindControl("updateOption")).Checked = true;
                            break;
                        case SecurityLevel.Create:
                            ((GroupRadioButton)e.Item.FindControl("createOption")).Checked = true;
                            break;
                        case SecurityLevel.Delete:
                            ((GroupRadioButton)e.Item.FindControl("deleteOption")).Checked = true;
                            break;
                        case SecurityLevel.Grant:
                            ((GroupRadioButton)e.Item.FindControl("grantOption")).Checked = true;
                            break;
                        default:
                            throw new Exception("Unknown security level: " + permission.SecurityLevel.ToString());
                    }
                }




                if (inheritedPermission == null)
                {
                    ((Literal)e.Item.FindControl("inheritedInfo")).Text = String.Format("{0} ({1})",
                        Translator.Translate("Security", "NoInheritedSecurity"),
                        Translator.Translate("Security", "Grant"));
                }
                else
                {
                    ((Literal)e.Item.FindControl("inheritedInfo")).Text = String.Format("{0} ({1})",
                        Translator.Translate("Security", inheritedPermission.SecurityLevel.ToString()),
                        NodeTypeManager.GetNodeType(inheritedPermission.InheritedFromObjectId).Name);
                }
            }
        }

        #endregion

        #region Properties

        //NodeId or TypeId
        public Guid ObjectId
        {
            get
            {
                object o = ViewState["ObjectId"];
                if (o == null)
                    return Guid.Empty;
                return (Guid)o;
            }
            set { ViewState["ObjectId"] = value; }
        }

        public IEnumerable<Permission> Permissions
        {
            get
            {
                return _permissions.AsEnumerable();
            }
        }

        public virtual PermissionType PermissionType
        {
            get { return PermissionType.TypePermission; }
        }

        #endregion

        #region Methods

        private void BuildControl(IEnumerable<GroupNode> groups)
        {
            groupRepeater.DataSource = groups;
            groupRepeater.DataBind();
        }

        private List<Permission> CompilePermissions()
        {
            if (IsPostBack)
            {
                List<Permission> permissions = new List<Permission>();

                foreach (RepeaterItem item in groupRepeater.Items)
                {
                    Guid key;

                    if ((item.ItemType == ListItemType.Item ||
                        item.ItemType == ListItemType.AlternatingItem) &&
                        !((GroupRadioButton)item.FindControl("inheritedOption")).Checked &&
                        StringHelper.IsGuid(((HiddenField)item.FindControl("dataFieldId")).Value, out key))
                    {
                        if (((GroupRadioButton)item.FindControl("readOption")).Checked)
                            permissions.Add(new Permission(ObjectId, key, SecurityLevel.Read, PermissionType));
                        else if (((GroupRadioButton)item.FindControl("updateOption")).Checked)
                            permissions.Add(new Permission(ObjectId, key, SecurityLevel.Update, PermissionType));
                        else if (((GroupRadioButton)item.FindControl("createOption")).Checked)
                            permissions.Add(new Permission(ObjectId, key, SecurityLevel.Create, PermissionType));
                        else if (((GroupRadioButton)item.FindControl("deleteOption")).Checked)
                            permissions.Add(new Permission(ObjectId, key, SecurityLevel.Delete, PermissionType));
                        else if (((GroupRadioButton)item.FindControl("grantOption")).Checked)
                            permissions.Add(new Permission(ObjectId, key, SecurityLevel.Grant, PermissionType));
                    }
                }

                return permissions;
            }

            return null;
        }

        #endregion

    }
}